package net.odtel.mailadmin.controller;

import net.odtel.mailadmin.model.EmailAccount;
import net.odtel.mailadmin.services.EmailAccountService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

@Component
public class EmailAccountValidator implements Validator {

	private EmailAccountService emailAccountService;

	public void setEmailAccountService(EmailAccountService emailAccountService) {
		this.emailAccountService = emailAccountService;
	}

	private static final Logger logger = LoggerFactory
			.getLogger(EmailAccountValidator.class);

	public boolean supports(Class clazz) {
		return EmailAccount.class.isAssignableFrom(clazz);
	}

	public void validate(Object target, Errors errors) {
		logger.info("Start Validator");
		EmailAccount emailAccount = (EmailAccount) target;
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username",
				"field.required", "Required field");

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
				"field.required", "Required field");

		if (emailAccount.getDomain() != null 
				&& !emailAccount.getDomain().isEmpty()
				&& !emailAccountService.inDomain(emailAccount.getDomain())) {
			errors.rejectValue("domain", "domain.notexist", "Domain not exist");
		}
				
		if (emailAccount.getUsername() != null
				&& !emailAccount.getUsername().isEmpty()
				&& emailAccountService.ifExist(emailAccount.getUsername())) {
			errors.rejectValue("username", "user.exist", "User exist");
		}

		if (emailAccount.getQuota() == null
				|| emailAccount.getQuota().intValue() <= -1
				|| emailAccount.getQuota().intValue() > 1024 ) {
			errors.rejectValue("quota", "quota.incorrect", "Quota is incorrect");
		}
				
				

	}

}
